package com.myapp.foodapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;

public class CommentsListActivity extends AppCompatActivity {

    private ListView commentlistview;
    private List<CommentBean.DataBean> data;
    private TextView foodNameTv;
    private Button cancelBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comments_list);
        initView();
        showComments();
        initEvent();
    }

    private void initView() {
        commentlistview = findViewById(R.id.comments_list_view);
        foodNameTv = findViewById(R.id.cm_food_name_tv);
        cancelBtn = findViewById(R.id.cancel_btn);
    }

    private void initEvent() {
        commentlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //保存评论id
                UrlUtil.commentId = data.get(position).getId();

                Intent intent = new Intent(CommentsListActivity.this, CommentsDetailActivity.class);
                startActivity(intent);
            }
        });

        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
    private void showComments() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = UrlUtil.basePath + "/foodserver/comment/list/" + UrlUtil.foodId;

                    data = new Gson().fromJson(GainDataUtil.GainDataForGet(url), CommentBean.class).getData();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            commentlistview.setAdapter(new CommentsAdapter(CommentsListActivity.this, data));
                            foodNameTv.setText(UrlUtil.foodName);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}